#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        vector<vector<int>> memo(matrix.size(), vector<int>(matrix[0].size(), 0));
        int ret = 0;
        for (int i = 0; i < matrix.size(); i++)
            for (int j = 0; j < matrix[0].size(); j++) ret = max(ret, dfs(matrix, memo, i, j));
        return ret;
    }
    int dfs(vector<vector<int>>& matrix, vector<vector<int>>& memo, int x, int y)
    {
        if (memo[x][y]) return memo[x][y];
        int ret = 1;
        for (int k = 0; k < 4; k++)
        {
            int a = x + dx[k], b = y + dy[k];
            if (a >= 0 && a < matrix.size() && b >= 0 && b < matrix[a].size() && matrix[x][y] > matrix[a][b])
                ret = max(ret, dfs(matrix, memo, a, b) + 1);
        }
        memo[x][y] = ret;
        return ret;
    }
};